<template>
  <div class="upload">
    <el-upload
      action="#"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :http-request="upload"
      :file-list="fileList"
      :limit="1"
      :class="{ disabled: showImage }"
      :on-change="changeFile"
    >
      <p>上传图片</p>
    </el-upload>
    <el-dialog title="图片预览" :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      currentId: '',
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: []
    }
  },
  computed: {
    showImage () {
      return this.fileList.length === 1
    }
  },
  methods: {
    // 删除图片，定义fileList的时候，源码会自动帮我们生成uid
    handleRemove (file, fileList) {
      this.fileList = this.fileList.filter((item) => item.uid !== file.uid)
    },
    // 图片预览，得到图片的url，显示弹出层
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 文件状态改变时触发，file会触发多次
    changeFile (file, fileList) {
      this.fileList = fileList
    },
    // 上传文件之前钩子，检测文件类型
    beforeUpload (file) {
      //   console.log(file)
      // 检查类型
      const type = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!type.includes(file.type)) {
        return false
      }
      // 检查大小
      const maxSize = 5 * 1024 * 1024
      if (maxSize < file.size) {
        return false
      }
      this.currentId = file.uid
      return true
    },
    upload () {}
  }
}
</script>

<style scoped lang="less">
.upload {
  display: inline-block;
  width: 100px;
  height: 62px;
  margin-left: 5px;
  line-height: 40px !important;
  vertical-align: middle;
  /deep/.el-upload--picture-card {
    width: 100px !important;
    height: 62px !important;
    line-height: 40px !important;
    vertical-align: middle;
  }
  /deep/.el-upload-list__item {
    width: 100px !important;
    height: 62px !important;
    vertical-align: middle;
  }
  .disabled /deep/.el-upload--picture-card {
    display: none;
  }
}
</style>
